package com.jabo.douban.demo.domain.http;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @anthor JZheng3
 * @Time: 2020/3/2
 */
public class HttpManager {

    private volatile static HttpManager mInstance;
    private static final String BASE_URL = "https://api.tianapi.com/";
    public static final int HTTP_CONNECT_TIMEOUT = 15;
    public static final int HTTP_READ_TIMEOUT = 45;
    public static final int HTTP_WRITE_TIMEOUT = 55;

    private Retrofit mRetrofit;
    private HashMap<Class, Retrofit> mRetrofitHashMap;

    public static HttpManager getInstance() {
        if (mInstance == null) {
            synchronized (HttpManager.class) {
                if (mInstance == null) {
                    mInstance = new HttpManager();
                }
            }
        }
        return mInstance;
    }

    private HttpManager() {
        mRetrofitHashMap = new HashMap<>();
        initOkHttp();
    }

    private void initOkHttp() {
        //init okHttp
        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HTTP_WRITE_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new HttpInterceptor())
                .build();

        //init retrofit
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        mRetrofitHashMap.put(ApiService.class, mRetrofit);
    }

    public <T> T getService(Class<T> tClass) {
        Retrofit retrofit = mRetrofitHashMap.get(tClass);
        if (retrofit != null) {
            return retrofit.create(tClass);
        } else {
            return null;
        }
    }


}
